//
//  Loadsingle.m
//  ZLShang
//
//  Created by wangguangming on 15/7/24.
//  Copyright © 2015年 Amber. All rights reserved.
//

#import "Loadsingle.h"
#import "Base.h"
#import "JsonTool.h"
#import <CommonCrypto/CommonDigest.h>
#import "AFNetworking.h"
#import "UIKit+AFNetworking.h"
#import "MD5Encode.h"


#import "Loadviewcontroller.h"
#import "AFURLRequestSerialization.h"
#import "UserModel.h"
static Loadsingle *single=nil;
@implementation Loadsingle

{
    NSMutableData *reciveData;
}
+(Loadsingle *)single
{
    if (single==nil) {
        single=[[Loadsingle alloc] init];
        
    }
    return single;
    
}



- (void)login
{
    
    NSString *documents=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    
        //2.拼接文件路径
    NSString *file=[documents stringByAppendingString:@"/devetoken.plist"];
    
  
    
    NSArray *readarray=[NSArray arrayWithContentsOfFile:file];
        // NSLog(@"%@",readarray[0]);

        //真机
    
//    NSString *result  =[[ NSString alloc] initWithData:readarray[0] encoding:NSUTF8StringEncoding];
//    NSString *s=[result substringFromIndex:1];
//    NSString *ss=[s substringToIndex:s.length-1];
//    NSLog(@"%@",ss);
//    NSString *urlSrting=[NSString stringWithFormat:@"%@/api/zls/users/login?deviceToken=%@&deviceType=1",URL,ss];
//  
    
    
        NSString *urlSrting=[NSString stringWithFormat:@"%@/api/zls/users/login?deviceToken=asdasdsadsadadad&deviceType=1",URL];
    [MD5Encode md5:self.password];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    
              //2.设置登录参数
   

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlSrting]];
    
//    [request setValue:@(1) forKey:@"deviceType"];
//    [request setValue:@"fnwregnernernkl v" forKey:@"deviceToken"];
    [request setHTTPMethod:@"GET"];
    
    
    NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.account, [MD5Encode md5:self.password]];
    NSData *string = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding];
    NSString *encoding64 = [string base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    NSString *header = [NSString stringWithFormat:@"Basic %@",encoding64];
    
    
    [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
   
   
    
    [request setHTTPShouldHandleCookies:YES];
    
    [request setValue:header forHTTPHeaderField:@"Authorization"];
    
    
//    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]
   [NSURLConnection connectionWithRequest:request delegate:self];
}


    //接收到服务器回应的时候调用此方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{
  
        reciveData = [NSMutableData data];
       
    
}

    //接收到服务器传输数据的时候调用，此方法根据数据大小执行若干次

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{
    
     [reciveData appendData:data];
           
}

    //数据传完之后调用此方法

-(void)connectionDidFinishLoading:(NSURLConnection *)connection

{
//    NSString *string = [[NSString alloc] initWithData:reciveData encoding:NSUTF8StringEncoding];
    
    NSDictionary *response = [NSJSONSerialization JSONObjectWithData:reciveData options:NSJSONReadingMutableLeaves error:nil];
    self.userArray=[NSMutableArray array];
    if ([response allValues].count>3)
        {
        UserModel *userModer=[[UserModel alloc] init];
        [userModer  setValuesForKeysWithDictionary:response];
       
        [self.userArray addObject:userModer];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"do" object:self];
        [self write];
        }
    else
        {
        UIAlertView *a=[[UIAlertView alloc] initWithTitle:@"提醒" message:@"账号或密码错误" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        [a show];
        }
        NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
  
}

    //网络请求过程中，出现任何错误（断网，连接超时等）会进入此方法

-(void)connection:(NSURLConnection *)connection

 didFailWithError:(NSError *)error

{
    UIAlertView *a=[[UIAlertView alloc] initWithTitle:@"提醒" message:@"网络错误" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
    [a show];
        //NSLog(@"%@",[error localizedDescription]);
}
-(void)loagout
{
    NSString *urlString=[NSString stringWithFormat:@"%@/api/zls/users/logout",URL];
    NSURL *url=[NSURL URLWithString:urlString];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    [request setHTTPShouldHandleCookies:YES];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *respose,NSData *data,NSError *error){
            // NSLog(@"respose==%@respose==%@ ",respose,error);
      [[NSNotificationCenter defaultCenter] postNotificationName:@"donot" object:self];   
      
         }];
    

}
-(void)write
{
    NSString *documents=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSString *file1=[documents stringByAppendingString:@"/usera.plist"];
    NSDictionary *d=[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%@",self.account] forKey:@"account"];
    NSDictionary *d1=[NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%@",self.password] forKey:@"password"];
     NSString *file2=[documents stringByAppendingString:@"/userp.plist"];
    [d writeToFile:file1 atomically:YES];
    [d1 writeToFile:file2 atomically:YES];

}
@end
